<template>
    <template v-if="viewData.current === undefined">
        <el-empty description="未选中组件"></el-empty>
    </template>
    <template v-else>
        <pt-form ref="formRef" :rules="viewData.rules" :key="viewData.key" />
    </template>
</template>

<script lang="ts" setup>
import type { IFormConfig } from '@pangtou/form'
import type { context } from '../lib/context'
import { current, byId } from '../lib/form'
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import { uniqueId } from '@/utils'

const formRef = ref()

const viewData = reactive<{
    current?: string
    rules: IFormConfig
    key: string
    ctx?: context
}>({
    current: undefined,
    ctx: undefined,
    key: uniqueId(),
    rules: {
        buttons: false,
        props: { labelPosition: 'right', labelWidth: '120px' },
        rules: [],
    },
})

const change = () => {
    if (current.value === '') {
        viewData.current = undefined
        return
    }
    viewData.current = current.value
    viewData.ctx = byId(viewData.current) as any
    viewData.rules.rules = viewData.ctx!.getFormRules()
    viewData.key = uniqueId()
    nextTick().then(() => {
        formRef.value?.action.on('update', (param: { field: string; value: any }) => {
            viewData.ctx!.setFormValue(param.field, param.value)
        })
    })
}

watch(
    () => current.value,
    () => {
        change()
    },
)

onMounted(() => {
    change()
})
</script>
